﻿using System.Collections;

namespace DimensionsHelper.LanguageService.Syntax;

public abstract class PreNodeList : SourceNode, IReadOnlyList<SourceNode>
{
    protected internal PreNodeList(SourceNode? parent, SyntaxKinds kind) : base(parent, kind)
    {
        NodeListInternal = new SourceNodeList();
    }


    internal SourceNodeList NodeListInternal { get; }


    public SourceNode? First => NodeListInternal.Count == 0 ? null : NodeListInternal[0];


    public SourceNode? Last => NodeListInternal.Count == 0 ? null : NodeListInternal[^1];


    /// <summary>
    ///     如果列表是空，返回true。
    /// </summary>
    public override bool IsEmpty => NodeListInternal.Count == 0;


    public IEnumerator<SourceNode> GetEnumerator()
    {
        return NodeListInternal.GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }


    /// <summary>
    ///     列表的节点数量
    /// </summary>
    public int Count => NodeListInternal.Count;


    public SourceNode this[int index] => NodeListInternal[index];


    public bool Any()
    {
        return NodeListInternal.Count > 0;
    }


    protected void SetNullableFieldValue<T>(ref T? field, Predicate<T?>? emptyChecker,
        T? value) where T : SourceNode
    {
        if (field != null && (emptyChecker == null || !emptyChecker(field)))
        {
            NodeListInternal.Remove(field);
        }

        if (value != null && (emptyChecker == null || !emptyChecker(value)))
        {
            field = value;
            NodeListInternal.Add(value);
        }
    }


    public virtual void AddNode(SourceNode node)
    {
        NodeListInternal.Add(node);
        node.Parent = this;
    }


    public virtual void AddNodes<T>(IEnumerable<T> nodes) where T : SourceNode
    {
        foreach (T node in nodes)
        {
            AddNode(node);
        }
    }
}